<template>
  <div id="payForDriver">
    <pub-header title="支付运费"></pub-header>
    <div class="notice-cell">支付前请确保司机（快递员）已上门取货！</div>
    <div style="margin: 0.2rem;">

      <group>
        <div class="vux-x-input weui-cell weui-vcode">
          <div class="weui-cell__hd">
            <label class="weui-label" style="width: 5em;">金额</label>
          </div>
          <div class="weui-cell__bd weui-cell__primary">
            <input class="weui-input" @input="keyUp" placeholder="请输入金额" v-model="money" />
          </div>
        </div>
      </group>

      <group title="请选择支付方式">
        <checker v-model="paytype" default-item-class="list-radio" selected-item-class="list-radio-selected">
          <checker-item value="yue" class="vux-1px-b flex flex-middle flex-space-between">
            <i class="icon icon-yue"></i>
            <span class="flex-auto">余额支付</span>
            <span class="info">可用余额: {{ yue }}元</span>
            <i class="icon icon-quan1"></i>
          </checker-item>
          <checker-item value="wechat" class="vux-1px-b flex flex-middle flex-space-between">
            <i class="icon icon-wechat"></i>
            <span class="flex-auto">微信支付</span>
            <i class="icon icon-quan1"></i>
          </checker-item>
        </checker>
      </group>
    </div>
    <div style="margin-top: 0.2rem; padding: 0.2rem;">
      <x-button type="primary" :show-loading="loading" action-type="button" @click.native="handleRecharge">{{ btn }}</x-button>
    </div>
  </div>
</template>
<script>
import { Cell, Checker, CheckerItem } from 'vux'
import PubHeader from '../components/PubHeader.vue'

export default{
  components: {
    PubHeader,
    Cell,
    CheckerItem,
    Checker
  },
  beforeRouteEnter(to, from, next) {
    if(window.localStorage.openid){
      next()
    } else {
      window.location = $config.wechatHost + '/pay/wechat/wechat.php'
    }
    next()
  },
  watch: {
    money: function (val) {
      if(val > this.yue && this.paytype === 'yue') {
        this.money = this.t_money = this.yue
        this.$vux.toast.text('可用余额'+ this.yue + '元' , 'middle')
      }
    },
    paytype: function (val) {
      if(val === 'yue' && this.money > this.yue) {
        this.money = this.t_money = this.yue
        this.$vux.toast.text('可用余额'+ this.yue + '元' , 'middle')
      }
    }
  },
  created() {

    if(!this.$route.query.num){
      this.$router.push('/')
      this.$vux.toast.text('参数不存在', 'middle')
      return
    }


    this.openid = window.localStorage.openid
    this.$http.post($config.host + '/api/Account/getrechargeGongZhongWxpayconf', qs.stringify({
      url: 'http://wap.tuniaoapp.com/?#/payForDriver',
      uid: this.$store.state.userInfo.uid,
      client: $config.client_type,
      device: $config.device_type,
      token: this.$store.state.userInfo.token
    })).then((res) => {
      const data = res.data
      this.$wechat.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: data.appId, // 必填，公众号的唯一标识
        timestamp: data.timestamp, // 必填，生成签名的时间戳
        nonceStr: data.nonceStr, // 必填，生成签名的随机串
        signature: data.signature,// 必填，签名，见附录1
        jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      });
    })
    .catch((error) => {
      this.$vux.toast.text($config.errWechatMsg, 'middle')
    })

    this.getAccount()
  },
  data() {
    return {
      yue: '',
      paytype: 'yue',
      money: '',
      t_money: undefined,
      openid: '',
      loading: false,
      btn: '确认支付',
      total_money: 0,
      chajia: 0
    }
  },
  methods: {
    getAccount() {
      this.$http.post($config.host + '/api/Account/getMyMoney', qs.stringify({
        uid: this.$store.state.userInfo.uid,
        client: $config.client_type,
        device: $config.device_type,
        token: this.$store.state.userInfo.token
      })).then(res => {
        const {code, data, msg} = res.data
        if(code == 1 && data) {
          this.isLoading = true
          this.yue = parseFloat(data.money)
        } else if (code == '3') {
          this.$vux.toast.text($config.loginErrMsg, 'middle')
          this.$router.push({path: '/logout'})
        } else {
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch(err => {
        this.$vux.toast.text($config.errMsg, 'middle')
      })
    },
    keyUp() {
      if (!this.money.match(/^\d*?\.?\d{0,2}?$/)){
        if(this.t_money === undefined){
          this.t_money = '';
        }
        this.money = this.t_money;
      } else {
        this.t_money = this.money;
      }
    },
    //点击支付按钮触发
    handleRecharge() {
      if (!this.money.match(/^[0-9]+(.[0-9]{1,2})?$/) || !this.money || this.money <= 0){
        this.$vux.toast.text('金额填写错误', 'middle')
        return false
      }
      this.loading = true
      //检查余额是否足够
      //this.checkBalance()
      if(this.paytype == 'yue') {
        this.payForBalance()
      } else if(this.paytype == 'wechat') {
        this.payDifference()
      }
    },
    //检查余额是否足够
    checkBalance() {
      this.$http.post($config.host + '/api/Account/payYunFieCheck', qs.stringify({
        money: this.money,
        uid: this.$store.state.userInfo.uid,
        num: this.$route.query.num,
        client: $config.client_type,
        device: $config.device_type,
        token: this.$store.state.userInfo.token
      })).then((res) => {
        const { data, code, msg } = res.data
        if(code == 55) {
          this.$vux.confirm.show({
            title: '<i class="icon icon-gantanhao"></i>',
            content: '系统将从您的余额中直接扣除' + this.money + '元',
            confirmText: '确认扣除',
            cancelText: '取消',
            onConfirm: () => {
              this.payForBalance()
            },
            onCancel: () => {
              this.loading = false
            }
          })
        } else if (code == 56) {
          this.total_money = data.total_money
          this.chajia = data.chajia
          this.payDifference()
        } else {
          this.loading = false
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch(err => {
        this.loading = false
        this.$vux.toast.text($config.errMsg, 'middle')
      })

    },
    //直接用余额支付
    payForBalance() {
      this.$http.post($config.host + '/api/Account/payYunFieYueAff', qs.stringify({
        money: this.money,
        uid: this.$store.state.userInfo.uid,
        num: this.$route.query.num,
        client: $config.client_type,
        device: $config.device_type,
        token: this.$store.state.userInfo.token
      })).then((res) => {
        const { code, msg } = res.data
        if(code == 1) {
          this.$vux.toast.text('运费支付成功', 'middle')
          this.$router.go(-1)
        } else {
          this.loading = false
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch(err => {
        this.loading = false
        this.$vux.toast.text($config.errMsg, 'middle')
      })
    },
    //直接支付
    payDifference() {
      this.$http.post($config.host + '/api/Account/rechargeYunFeiGongZhongWxpay', qs.stringify({
        openid: this.openid,
        //total_money: this.total_money,
        money: this.money,
        uid: this.$store.state.userInfo.uid,
        num: this.$route.query.num,
        client: $config.client_type,
        device: $config.device_type,
        token: this.$store.state.userInfo.token
      })).then((res) => {
        const { data, code, msg } = res.data
        if(code == 1) {
          this.$wechat.chooseWXPay({
            timestamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success: res => {
              this.$vux.toast.text('运费支付成功', 'middle')
              this.$router.go(-1)
            },
            cancel: res => {
              this.loading = false
            }
          })
        } else {
          this.loading = false
          this.$vux.toast.text(msg, 'middle')
        }
      }).catch(error => {
        this.loading = false
        this.$vux.toast.text($config.errMsg, 'middle')
      })
    }

  }
}
</script>
